package pjkanri.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pjkanri.dao.DAOException;
import pjkanri.entity.Account;
import pjkanri.service.AccountService;

/**
 * Servlet implementation class AccountServlet
 */
@WebServlet("/account")
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		// リクエスト・パラメーターの取得
		String email = request.getParameter("email");
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		
		String status = request.getParameter("status"); // Update status
//		System.out.println("status --->>> " + status);
		
		// Update 

		try {
			if (status.isEmpty() || status == null ) // insert
			{
//				System.out.println("Insert");
				AccountService.insert(new Account(email, name, password));
			}
			else
			{
				// セッション管理開始
				HttpSession session = request.getSession();
				
				Account account = (Account) session.getAttribute("account");
				account.setEmail(email);
				account.setPassword(password);
				
				// セッション・オブジェクトにAccountオブジェクトをセット
				session.setAttribute("account", account);
				
				AccountService.update(account);
			}
		} catch (DAOException e) {
			e.printStackTrace();
		}

		String forwardPath = "index.jsp";

		// 転送処理
		request.getRequestDispatcher(forwardPath).forward(request, response);

	}

}
